document.addEventListener('DOMContentLoaded', ()=> {
    // 获取当前页面的参数
    const urlParams = new URLSearchParams(window.location.search);
    const repoPath = urlParams.get('repoPath') || '';
    const from = urlParams.get('from') || 'HEAD~1';
    const to = urlParams.get('to') || 'HEAD';
    
    // 生成当前会话的唯一标识
    const sessionKey = `${repoPath}_${from}_${to}`;
    
    // 1. 初始化时读取 localStorage
    const allComments = JSON.parse(localStorage.getItem('allComments') || '{}');
    let comments = allComments[sessionKey] || [];    // 当前会话的评论数据
    
    function saveComments() {
      allComments[sessionKey] = comments;
      localStorage.setItem('allComments', JSON.stringify(allComments));
    }
    
    // 清空当前会话的评论
    function clearCurrentComments() {
      comments = [];
      delete allComments[sessionKey];
      localStorage.setItem('allComments', JSON.stringify(allComments));
      // 清除页面上的评论行
      document.querySelectorAll('.comment-row').forEach(el => el.remove());
    }

    // 初始化时恢复已保存的评论显示
    function restoreComments() {
      comments.forEach(comment => {
        const fileWrappers = document.querySelectorAll('.d2h-file-wrapper');
        for (const fileWrap of fileWrappers) {
          const fileName = fileWrap.querySelector('.d2h-file-name').textContent.trim();
          if (fileName === comment.file) {
            insertCommentAfterLines(fileWrap, comment);
            break;
          }
        }
      });
    }

    // 在指定行后插入评论
    function insertCommentAfterLines(fileWrap, comment) {
      const table = fileWrap.querySelector('.d2h-diff-table');
      const tbody = table.querySelector('tbody');
      const rows = Array.from(tbody.querySelectorAll('tr'));
      
      // 找到目标行 - 使用右侧commit的行号为准
      let targetRow = null;
      let targetRowIndex = -1;
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        // 优先使用右侧行号（.line-num2），如果没有则使用左侧行号（.line-num1）
        const rightLineNum = row.querySelector('.line-num2');
        const leftLineNum = row.querySelector('.line-num1');
        
        if (rightLineNum && +rightLineNum.textContent === comment.endLine) {
          targetRow = row;
          targetRowIndex = i;
          break;
        } else if (leftLineNum && +leftLineNum.textContent === comment.endLine) {
          targetRow = row;
          targetRowIndex = i;
          break;
        }
      }
      
      if (targetRow && targetRowIndex >= 0) {
        // 创建评论行
        const commentRow = document.createElement('tr');
        commentRow.className = 'comment-row';
        commentRow.dataset.commentId = comment.id;
        
        // 获取表格的列数（通常是3列：左侧行号、右侧行号、代码内容）
        const firstRow = tbody.querySelector('tr');
        const colCount = firstRow ? firstRow.cells.length : 3;
        
        // 创建评论行的HTML结构
        let commentRowHTML = '';
        for (let i = 0; i < colCount; i++) {
          if (i === colCount - 1) {
            // 最后一列放置评论内容
            commentRowHTML += `
              <td class="comment-cell" colspan="1">
                <div class="my-comment">
                  <div class="comment-header">
                    <span>${comment.file} [${comment.startLine}${ comment.startLine===comment.endLine? '' : ' - '+comment.endLine }]</span>
                    <button class="edit">编辑</button>
                    <button class="delete">删除</button>
                  </div>
                  <div class="comment-body">${comment.text}</div>
                </div>
              </td>
            `;
          } else {
            // 其他列保持为空，但保持表格结构
            commentRowHTML += '<td class="comment-cell"></td>';
          }
        }
        
        commentRow.innerHTML = commentRowHTML;
        
        // 将评论行插入到目标行后面
        tbody.insertBefore(commentRow, targetRow.nextSibling);
        
        // 绑定删除和编辑事件
        bindCommentEvents(commentRow, comment);
      }
    }

    // 绑定评论的删除和编辑事件
    function bindCommentEvents(commentRow, comment) {
      // 删除评论
      commentRow.querySelector('.delete').addEventListener('click', ()=>{
        // 删除评论行
        commentRow.remove();
        const idx = comments.findIndex(c=>c.id===comment.id);
        if (idx>=0) comments.splice(idx,1);
        saveComments();
      });
      
      // 编辑评论
      commentRow.querySelector('.edit').addEventListener('click', ()=>{
        // 先删旧显示
        commentRow.remove();
        const idx = comments.findIndex(c=>c.id===comment.id);
        const old = comments.splice(idx,1)[0];
        saveComments();
        
        // 选中原行以便弹框位置合理
        clearHighlight();
        const fileWrappers = document.querySelectorAll('.d2h-file-wrapper');
        let targetFileWrap = null;
        for (const fileWrap of fileWrappers) {
          const fileName = fileWrap.querySelector('.d2h-file-name').textContent.trim();
          if (fileName === old.file) {
            targetFileWrap = fileWrap;
            break;
          }
        }
        
        if (targetFileWrap) {
          const allTrs = Array.from(targetFileWrap.querySelectorAll('.d2h-diff-table tbody tr'));
          allTrs.forEach(tr=>{
            // 获取行号，优先使用右侧行号
            const rightNum = tr.querySelector('.line-num2');
            const leftNum = tr.querySelector('.line-num1');
            const num = rightNum ? +rightNum.textContent : (leftNum ? +leftNum.textContent : 0);
            
            if (num>=old.startLine && num<=old.endLine) {
              tr.classList.add('line-selected');
              selectedTrs.add(tr);
            }
          });
          
          // 弹框并填值
          const firstSelectedTr = Array.from(selectedTrs)[0];
          if (firstSelectedTr) {
            const firstRect = firstSelectedTr.getBoundingClientRect();
            showBox(firstRect.right+window.scrollX, firstRect.top+window.scrollY);
            box.querySelector('#comment-text').value = old.text;
          }
        }
      });
    }

    let isSelecting = false;
    let startTr = null;     // 拖选起始的 <tr>
    let selectedTrs = new Set();
  
    // 1）创建评论弹层
    const box = document.createElement('div');
    box.id = 'comment-box';
    box.style.position = 'absolute';
    box.style.display  = 'none';
    box.innerHTML = `
      <textarea id="comment-text" rows="3" style="width:300px"></textarea>
      <div style="text-align:right;margin-top:4px">
        <button id="comment-save">保存</button>
        <button id="comment-cancel">取消</button>
      </div>`;
    document.body.appendChild(box);
  
    // helper：清空高亮
    function clearHighlight(){
      selectedTrs.forEach(tr=>tr.classList.remove('line-selected'));
      selectedTrs.clear();
    }
    // helper：收集所有代码行对应的 <tr>
    const allTrs = Array.from(
      document.querySelectorAll('.d2h-file-wrapper table.d2h-diff-table tbody tr')
    );
  
    // 2）给每行代码区域（右侧 <pre>）绑定鼠标事件
    allTrs.forEach(tr => {
      const ln = tr.querySelector('.d2h-code-linenumber');
      if (!ln) return;
  
      // 按下开始选
      ln.addEventListener('mousedown', e=>{
        e.preventDefault();
        clearHighlight();
        isSelecting = true;
        startTr = tr;
        selectedTrs.add(tr);
        tr.classList.add('line-selected');
      });
  
      // 点击单行时直接弹评论框
      ln.addEventListener('click', e=>{
        e.preventDefault();
        clearHighlight();
        selectedTrs.add(tr);
        tr.classList.add('line-selected');
        const r = tr.getBoundingClientRect();
        showBox(r.right + window.scrollX, r.top + window.scrollY);
      });
    });
  
    // 拖动过程中高亮区间
    document.addEventListener('mousemove', e=>{
      if (!isSelecting) return;
      const tgt = e.target;
      if (tgt.closest('tr')) {
        clearHighlight();
        const endTr = tgt.closest('tr');
        const i1 = allTrs.indexOf(startTr);
        const i2 = allTrs.indexOf(endTr);
        const [a,b] = i1<=i2 ? [i1,i2] : [i2,i1];
        for (let i=a; i<=b; i++){
          allTrs[i].classList.add('line-selected');
          selectedTrs.add(allTrs[i]);
        }
      }
    });
  
    // 松开鼠标：结束选区并弹评论框
    document.addEventListener('mouseup', e=>{
      if (!isSelecting) return;
      isSelecting = false;
      if (selectedTrs.size>0) {
        showBox(e.pageX, e.pageY);
      }
    });
  
    // 显示评论弹层
    function showBox(x,y){
      box.style.left = x + 'px';
      box.style.top  = y + 'px';
      box.style.display = 'block';
      box.querySelector('#comment-text').value = '';
    }
    function hideBox(){
      box.style.display = 'none';
      clearHighlight();
    }
  
    // 3）取消按钮
    box.querySelector('#comment-cancel').addEventListener('click', hideBox);
  
    // 4）保存评论
    box.querySelector('#comment-save').addEventListener('click', ()=>{
      const txt = box.querySelector('#comment-text').value.trim();
      if (!txt) { alert('评论不能为空'); return; }
  
      // 排序选中的 tr 找到首尾行号 - 优先使用右侧commit的行号
      const sorted = Array.from(selectedTrs).sort((a,b)=>{
        const aRightNum = a.querySelector('.line-num2');
        const bRightNum = b.querySelector('.line-num2');
        const aLeftNum = a.querySelector('.line-num1');
        const bLeftNum = b.querySelector('.line-num1');
        
        // 优先使用右侧行号，如果没有则使用左侧行号
        const aNum = aRightNum ? +aRightNum.textContent : (aLeftNum ? +aLeftNum.textContent : 0);
        const bNum = bRightNum ? +bRightNum.textContent : (bLeftNum ? +bLeftNum.textContent : 0);
        
        return bNum - aNum;
      });
      
      // 获取首尾行号，优先使用右侧行号
      const getLineNumber = (tr) => {
        const rightNum = tr.querySelector('.line-num2');
        const leftNum = tr.querySelector('.line-num1');
        return rightNum ? +rightNum.textContent : (leftNum ? +leftNum.textContent : 0);
      };
      
      const endLine = getLineNumber(sorted[0]);
      const startLine = getLineNumber(sorted[sorted.length-1]);
      const fileWrap  = sorted[0].closest('.d2h-file-wrapper');
      const fileName  = fileWrap.querySelector('.d2h-file-name').textContent.trim();
  
      // 创建评论对象
      const cid = Date.now();
      const comment = { id:cid, file:fileName, startLine, endLine, text:txt };
      
      // 插入评论到页面
      insertCommentAfterLines(fileWrap, comment);
      
      // 保存到内存和localStorage
      comments.push(comment);
      saveComments();

      hideBox();
    });

    // 导出按钮
    const exportBtn = document.getElementById('export-btn');
    if (exportBtn) {
      exportBtn.addEventListener('click', () => {
        if (comments.length === 0) {
          alert('没有批注，无法导出');
          return;
        }
        
        // 获取当前页面的 repoPath 参数
        const urlParams = new URLSearchParams(window.location.search);
        const repoPath = urlParams.get('repoPath') || '';
        
        fetch('/export', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ comments, repoPath })
        })
          .then(res => {
            if (!res.ok) {
              throw new Error('导出失败');
            }
            return res.blob();
          })
          .then(blob => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'comments.csv';
            document.body.appendChild(a);
            a.click();
            a.remove();
            URL.revokeObjectURL(url);
          })
          .catch(err => {
            console.error(err);
            alert('导出失败：' + err.message);
          });
      });
    }
    
    // 清空按钮
    const clearBtn = document.getElementById('clear-btn');
    if (clearBtn) {
      clearBtn.addEventListener('click', () => {
        if (comments.length === 0) {
          alert('当前没有批注');
          return;
        }
        if (confirm('确定要清空所有批注吗？此操作不可恢复。')) {
          clearCurrentComments();
          alert('批注已清空');
        }
      });
    }

    // 页面加载完成后恢复评论显示
    restoreComments();
  });
  